package com.bite.bite_forum.services.Impl;
import com.bite.bite_forum.common.AppConfig;
import com.bite.bite_forum.common.AppResult;
import com.bite.bite_forum.common.ResultCode;
import com.bite.bite_forum.dao.UserMapper;
import com.bite.bite_forum.exception.ApplicationException;
import com.bite.bite_forum.model.User;
import com.bite.bite_forum.services.IUserService;
import com.bite.bite_forum.utils.MD5Utils;
import com.bite.bite_forum.utils.StringUtils;
import com.bite.bite_forum.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //非空校验
        if(user == null){
          log.info(ResultCode.ERROR_IS_NULL.getMessage());
          throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //查询用户是否存在
        User existUser = userMapper.selectByUsername(user.getUsername());
        if(existUser != null) {
            log.info(ResultCode.AILED_USER_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //准备数据
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int row = userMapper.insertSelective(user);
        if(row == 0){
            log.info(ResultCode.FAILED_CREATE.getMessage());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增成功 userId == " + user.getId());

    }

    @Override
    public User selectByUserName(String username) {
        User user = userMapper.selectByUsername(username);
        if(user == null){
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return user;
    }

    @Override
    public User login(String username, String password) {
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectByUserName(username);
        //密码校验
        boolean result = MD5Utils.verifyOriginalAndCiphertext(password, user.getSalt(), user.getPassword());
        if(!result){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }


    @Override
    public User selectById(HttpServletRequest request, Long id) {
        User user = null;
        //1 id为空 返回登录信息
        if(id == null){
            HttpSession session = request.getSession(false);
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
                log.info(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
            }
            user = (User)session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //2 id不为空 返回指定用户信息
            user = userMapper.selectByPrimaryKey(id);
        }
        return user;
    }

    @Override
    public int addArticleCountById(Long id) {
        if(id == null || id < 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        return userMapper.updateByPrimaryKeySelective(updateUser);
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //校验参数
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户是否被禁言
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //更新发帖数
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if(user.getArticleCount() < 0){
            user.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.info(ResultCode.ERROR_SERVICES.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES.getMessage()));
        }

    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if (user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //验证用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null || existsUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        updateUser.setId(existsUser.getId());
        //定义标志位
        Boolean checkAttr = false;

        //修改用户名
        if (!StringUtils.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())) {
            User checkUser = userMapper.selectByUsername(user.getUsername());
            if (checkUser != null && checkUser.getDeleteState() != 1) {
                log.info(ResultCode.AILED_USER_EXISTS.getMessage());
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }

        //修改昵称
        if (!StringUtils.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

        //修改性别
        if (user.getGender() != null
                && user.getGender() != existsUser.getGender()) {
            if (user.getGender() > 2 || user.getGender() < 0) {
                user.setGender((byte) 2);
            }
            updateUser.setGender(user.getGender());
            checkAttr = true;
        }
        //修改邮箱
        if (!StringUtils.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        //修改电话
        if (!StringUtils.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        //修改个人简介
        if (!StringUtils.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }

        if(!checkAttr){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.info(ResultCode.ERROR_SERVICES.getMessage());
            throw new ApplicationException(ResultCode.ERROR_SERVICES.getMessage());
        }

    }

    @Override
    public User selectByPrimaryKey(Long id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        //校验参数
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验原密码是否正确
        String password = MD5Utils.md5salt(oldPassword, user.getSalt());
        if(!password.equals(user.getPassword())){
            log.info("原密码错误");
            throw new ApplicationException(AppResult.failed("原密码错误"));
        }
        //修改密码
        String salt = UUIDUtils.UUID_32();
        String updatePassword = MD5Utils.md5salt(newPassword, salt);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(updatePassword);
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.info(ResultCode.ERROR_SERVICES.getMessage());
            throw new ApplicationException(ResultCode.ERROR_SERVICES.getMessage());
        }
    }


}
